<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Sentinel;

class Simulate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(env('APP_ENV') == 'local'){
            $user = Sentinel::check();
            if(!$request->is('admin/*')){
                if(!$user || $user->is_admin){
                    $user = User::find(2);
                    Sentinel::login($user);
                    session(['userId' => $user->id]);
                    if($request->is('index') && env('APP_SIMULATE')){
                        $state['deviceCode'] = deviceCode();
                        $host = head($request->header()['host']);
                        return view('index')->with([
                             'state' => $state,
                             'host' => $host,
                             ]);
                    }
                }
            }else{
                if(env('APP_DEBUG') && (!$user || !$user->is_adminn)){
                    $user = User::find(1);
                    Sentinel::login($user);
                }
            }
        }
        return $next($request);
    }
}
